package com.dqp.cslggroup.Util;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.renderscript.*;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.dqp.cslggroup.UI.MyApplication.getContext;

/**
 * @Author
 * @Describe：所有与UI相关操纵的工具类
 */
public class UiUtils {

    private static final String TAG = UiUtils.class.getSimpleName();

    //在dialog.show()之后调用
    public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
        Window window = dlg.getWindow();
        assert window != null;
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        Display display = Objects.requireNonNull(wm).getDefaultDisplay(); //获取屏幕宽高
        Point point = new Point();
        display.getSize(point);
        WindowManager.LayoutParams layoutParams = window.getAttributes(); //获取当前对话框的参数值
        layoutParams.width = (int) (point.x * 0.7); //宽度设置为屏幕宽度的0.5
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; //高度设置为屏幕高度的0.5
        dlg.getWindow().setAttributes(lp);
    }

    public static int getScreenWidth(Context context) {

        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density1 = dm.density;
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        return width;
    }


    /**
     * 通过ID获取颜色值
     *
     * @param colorId
     * @return
     */
    public static int getColor(Context mContext, int colorId) {
        return mContext.getResources().getColor(colorId);
    }

    /**
     * 通过ID获取View
     *
     * @param layoutId
     * @return
     */
    public static View getXmlVIew(Context mContext, int layoutId) {
        return View.inflate(mContext, layoutId, null);
    }

    /**
     * 通过ID获取 View Item 布局的View
     *
     * @param mContext
     * @param layoutId
     * @return
     */
    public static View getItemView(Context mContext, int layoutId) {
        return LayoutInflater.from(mContext).inflate(layoutId, null);
    }

    /**
     * dp转换px
     *
     * @param dp
     * @return
     */
    public static int dp2px(Context mContext, int dp) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    /**
     * px转换dp
     *
     * @param px
     * @return
     */
    public static int px2dp(Context mContext, int px) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5);
    }

    /**
     * 通过arrayId获取string.xml里面指定的arrayId字符串数组
     *
     * @param arrayId
     * @return
     */
    public static String[] getStringArray(Context mContext, int arrayId) {
        return mContext.getResources().getStringArray(arrayId);
    }

    /**
     * 用于跳转Activity
     *
     * @param cls
     */
    public static void startActivity(Activity activity, Class<?> cls) {
        activity.startActivity(new Intent(activity, cls));
    }

    /**
     * 用于ForResult方式跳转Activity
     *
     * @param activity
     * @param cls
     * @param requestCode
     */
    public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode) {
        activity.startActivityForResult(new Intent(activity, cls), requestCode);
    }

    /**
     * 待参数的方式跳转Activity
     *
     * @param activity
     * @param cls
     * @param params
     * @param <T>
     */
    public static <T extends String> void startActivityForIntentParam(Context activity, Class<?> cls, Map<String, T> params) {
        Intent intent = new Intent(activity, cls);
        for (Map.Entry<String, T> entry : params.entrySet()) {
            intent.putExtra(entry.getKey(), entry.getValue());
        }
        activity.startActivity(intent);
    }

    /**
     * 获取其他Activity传过来的参数，转成Map集合
     *
     * @param activity
     * @param params
     * @return
     */
    public static Map receiveForIntentParam(Activity activity, String... params) {
        Intent intent = activity.getIntent();
        Map<String, String> mMap = new HashMap<>();
        for (int i = 0; i < params.length; i++) {
            mMap.put(params[i], intent.getStringExtra(params[i]));
        }
        return mMap.size() == 0 ? null : mMap;
    }

    /**
     * 设置EditText的hint字体大小
     *
     * @param editText
     * @param dpSize
     * @param textString
     */
    public static void setEditTextHint(EditText editText, int dpSize, String textString) {
        SpannableString ss = new SpannableString(textString);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dpSize, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_USER);
        editText.setHint(new SpannedString(ss));
    }

    /**
     * 设置EditText的hint颜色与字体大小
     *
     * @param editText
     * @param color
     * @param dpSize
     * @param textString
     */
    public static void setEditTextHint(EditText editText, int color, int dpSize, String textString) {
        SpannableString ss = new SpannableString(textString);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dpSize, true);
        editText.setHintTextColor(color);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_USER);
        editText.setHint(new SpannedString(ss));
    }

    /**
     * 设置EditText的hint颜色与字体大小
     *
     * @param editText
     * @param color
     * @param dpSize
     * @param textString
     * @param isDip
     */
    public static void setEditTextHint(EditText editText, int color, int dpSize, String textString, boolean isDip) {
        SpannableString ss = new SpannableString(textString);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dpSize, isDip);
        editText.setHintTextColor(color);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setHint(new SpannedString(ss));
    }

    /**
     * Java代码设置控件大小，这个方法没有什么卵用
     *
     * @param view   控件
     * @param width  宽度，单位：像素
     * @param height 高度，单位：像素
     */
    public static void setViewSize(View view, int width, int height) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }

    /**
     * 1、获取main在窗体的可视区域
     * 2、获取main在窗体的不可视区域高度
     * 3、判断不可视区域高度，之前根据经验值，在有些手机上有点不大准，现改成屏幕整体高度的1/3
     * 1、大于屏幕整体高度的1/3：键盘显示  获取Scroll的窗体坐标
     * 算出main需要滚动的高度，使scroll显示。
     * 2、小于屏幕整体高度的1/3：键盘隐藏
     *
     * @param main   根布局
     * @param scroll 需要显示的最下方View
     */
    public static ViewTreeObserver.OnGlobalLayoutListener addLayoutListener(final View main, final View scroll) {

        ViewTreeObserver.OnGlobalLayoutListener layoutListener = () -> {
            Rect rect = new Rect();
            main.getWindowVisibleDisplayFrame(rect);
            int screenHeight = main.getRootView().getHeight();
            int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
            if (mainInvisibleHeight > screenHeight / 4) {
                int[] location = new int[2];
                scroll.getLocationInWindow(location);
                int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                main.scrollTo(0, srollHeight);
            } else {
                main.scrollTo(0, 0);
            }
            //main.getViewTreeObserver().removeOnGlobalLayoutListener(this::onGlobalLayout);
        };
        main.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);

  /*      main.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            main.getWindowVisibleDisplayFrame(rect);
            int screenHeight = main.getRootView().getHeight();
            int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
            if (mainInvisibleHeight > screenHeight / 4) {
                int[] location = new int[2];
                scroll.getLocationInWindow(location);
                int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                main.scrollTo(0, srollHeight);
            } else {
                main.scrollTo(0, 0);
            }
        });*/
        return layoutListener;
    }


    public static Bitmap rsBlur(Context context, Bitmap source, int radius, float scale) {
        int width = Math.round(source.getWidth() * scale);
        int height = Math.round(source.getHeight() * scale);
        Bitmap inputBmp = Bitmap.createScaledBitmap(source, width, height, false);
        try {
            RenderScript renderScript = RenderScript.create(context);
            final Allocation input = Allocation.createFromBitmap(renderScript, inputBmp);   // Allocate memory for Renderscript to work with
            final Allocation output = Allocation.createTyped(renderScript, input.getType());
            ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));        // Load up an instance of the specific script that we want to use.
            scriptIntrinsicBlur.setInput(input);
            scriptIntrinsicBlur.setRadius(radius);        // Set the blur radius
            scriptIntrinsicBlur.forEach(output);     // Start the ScriptIntrinisicBlur
            output.copyTo(inputBmp);// Copy the output to the blurred bitmap
            renderScript.destroy();
        } catch (RSIllegalArgumentException e) {
            SharedPreferencesUtil.removeSp(context, "blur");
            ToastUtil.showToast("图片类型不支持模糊处理！可能会导致应用闪退！请更改图片！");
        }
        return inputBmp;
    }


    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap
                .createBitmap(
                        drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    public static void hideKeyboard(View view) {
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        assert manager != null;
        manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void openBrowser(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(intent);
    }

}